<template>
  <t-button
    v-permission="['system:budget-labor-costs-data:import']"
    @click="
      handleOpenDialog('update', {
        companyId: props.companyId,
        laborCostsId: props.laborCostsId,
        file:[]
      })
    "
  >
    导入费用
  </t-button>
  <!-- 自定义对话框 -->
  <custom-dialog
    ref="customDialogRef"
    v-slot="{ formData }"
    :api-map="{ update: importLaborCostsData }"
    header="导入费用"
    :on-before-save-data="handleDialogSaveData"
    @request-success="handleDialogRequestSuccess"
    :update-sucess-tip="'导入成功'"
  >
    <t-button @click="getTemplate" v-permission="['system:budget-labor-costs-data:get-import-template']">获取下载模板</t-button>
    <t-upload
        style="margin: 10px 0 0 0; "
        v-model="formData.file"
        theme="custom"
        accept=".xls,.xlsx"
        :abridge-name="[10, 8]"
        :multiple="false"
        :auto-upload="false"
        draggable
        @progress="onProgress"
      >
      <template #dragContent="params">
        <ul v-if="formData.file && formData.file.length" style="padding: 0">
          <li v-for="file in formData.file" :key="file.name" style="list-style-type: none">{{ file.name }}</li>
        </ul>
        <template v-else>
          <p v-if="params && params.dragActive">释放鼠标</p>
          <t-button v-else-if="progress < 1">上传excel文件</t-button>
        </template>
        <t-button v-if="formData.file && formData.file.length" size="small" style="margin-top: 36px">更换文件</t-button>
        <!-- <span>数据状态：{{params}}</span> -->
      </template>
    </t-upload>

  </custom-dialog>
  <!-- 导入结果 -->
  <t-dialog
    v-model:visible="visible"
    attach="body"
    destroy-on-close
    header="导入结果"
    @closed="handleClosed"
    :confirmBtn="null"
  >
  上传成功数量：{{createUsernames?.length}}条
  <br/>
  <div v-if="Object.keys(failureUsernames &&failureUsernames).length > 0">
    <div style="color: red; margin-top: 10px;">上传失败名称及原因:</div>
    <div 
      v-for="(message, key) in failureUsernames" 
      :key="key"
      style="margin: 5px 0;"
    >
      {{ key }}: {{ message }}
    </div>
  </div>
  </t-dialog>
</template>

<script setup lang="ts">
import { MessagePlugin, UploadFile } from 'tdesign-vue-next';
import { PropType, ref, useTemplateRef } from 'vue';

import { importLaborCostsData,getimportTemplateLaborCostsData } from '@/api/budget/labor-costs';
import CustomDialog from '@/components/custom/dialog/index.vue';
import { useUserStore } from '@/store';
import { request } from '@/utils/request';

import download from '@/utils/download';
// 用户仓库
const userStore = useUserStore();
// props
const props = defineProps({
  // 费用id
  companyId: {
    type: String,
    defuault: '',
  },
  laborCostsId: {
    type: String,
    defuault: '',
  },
});
const progress = ref(0);
const onProgress = ({ percent }) => {
  console.log('进度：', percent);
  progress.value = percent;
};

// 处理对话框保存数据
const handleDialogSaveData = (params: Record<string, any>)=>{
  console.log(params);
  
  if (!params.file || params.file.length === 0) {
    MessagePlugin.error('请先选择文件');
    return false;
  }
  const formData = new FormData();
  formData.append('file', params.file[0].raw); // 使用 raw 获取原始文件对象
  params.formData = formData
  

};
// emits
const emits = defineEmits(['requestSuccess']);
// 请求头
const headers = ref({
  Authorization: `Bearer ${userStore.token}`,
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog =async (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  console.log(result,'result');
  createUsernames.value = result.data.data.data.createUsernames||[]
  failureUsernames.value = result.data.data.data.failureUsernames||{}
  visible.value = true
  emits('requestSuccess', result);
};
const getTemplate = () => {
  getimportTemplateLaborCostsData()
    .then((data) => {
      download.excel(data, '费用模板');
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
}
// 导入结果
const createUsernames = ref([])
const failureUsernames = ref({})
// 导入对话框
const visible = ref(false)
const handleClosed = () => {
  visible.value = false
}
</script>
